import { defineStore } from 'pinia'
import type { Workflow } from '../types/workflow'

export const useWorkflowStore = defineStore('workflow', {
  state: () => {
    const stored = localStorage.getItem('workflows')
    return {
      workflows: JSON.parse(stored || '[]') as Workflow[],
      globalEnv: JSON.parse(localStorage.getItem('globalEnv') || '{}'),
    }
  },

  actions: {
    createWorkflow() {
      const newWorkflow: Workflow = {
        id: Date.now().toString(),
        name: '新建工作流',
        icon: 'i-mdi-flow-parallel',
        nodes: [],
        connections: [],
        env: {},
      }
      this.workflows.push(newWorkflow)
      this.saveToStorage()
      return newWorkflow
    },

    updateWorkflow(workflow: Workflow) {
      const index = this.workflows.findIndex(w => w.id === workflow.id)
      if (index !== -1) {
        this.workflows[index] = workflow
        this.saveToStorage()
      }
    },

    deleteWorkflow(id: string) {
      this.workflows = this.workflows.filter(workflow => workflow.id !== id)
      this.saveToStorage()
    },

    saveToStorage() {
      localStorage.setItem('workflows', JSON.stringify(this.workflows))
    },

    updateWorkflowEnv(workflowId: string, env: Record<string, string>) {
      const workflow = this.workflows.find(w => w.id === workflowId)
      if (workflow) {
        workflow.env = env
        this.saveToStorage()
      }
    },

    updateGlobalEnv(env: Record<string, string>) {
      this.globalEnv = env
      localStorage.setItem('globalEnv', JSON.stringify(env))
    },
  },
})
